<template>
  <div class="report-view">
    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 报告编辑区域 -->
        <el-card class="report-card">
          <template #header>
            <div class="card-header">
              <div class="template-select">
                <span>报告模板：</span>
                <el-select v-model="selectedTemplate" @change="loadTemplate">
                  <el-option
                    v-for="template in templates"
                    :key="template.id"
                    :label="template.name"
                    :value="template.id"
                  />
                </el-select>
              </div>
              <div class="actions">
                <el-button-group>
                  <el-button type="primary" @click="saveReport">
                    保存
                  </el-button>
                  <el-button type="success" @click="exportPDF">
                    导出PDF
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <div class="report-content">
            <!-- 报告头部信息 -->
            <div class="report-header">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="患者姓名">
                  {{ patientInfo.name }}
                </el-descriptions-item>
                <el-descriptions-item label="检查日期">
                  {{ patientInfo.examDate }}
                </el-descriptions-item>
                <el-descriptions-item label="检查类型">
                  {{ patientInfo.examType }}
                </el-descriptions-item>
                <el-descriptions-item label="检查编号">
                  {{ patientInfo.examId }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 影像展示区域 -->
            <div class="image-gallery">
              <h4>关键影像</h4>
              <el-row :gutter="10">
                <el-col :span="8" v-for="image in keyImages" :key="image.id">
                  <el-card :body-style="{ padding: '0px' }">
                    <img :src="image.url" class="key-image">
                    <div class="image-caption">
                      {{ image.description }}
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>

            <!-- 报告主体 -->
            <div class="report-body">
              <h4>检查所见</h4>
              <el-input
                v-model="reportContent.findings"
                type="textarea"
                :rows="6"
                placeholder="请输入检查所见..."
              />

              <h4>诊断意见</h4>
              <el-input
                v-model="reportContent.diagnosis"
                type="textarea"
                :rows="4"
                placeholder="请输入诊断意见..."
              />

              <h4>建议</h4>
              <el-input
                v-model="reportContent.suggestions"
                type="textarea"
                :rows="3"
                placeholder="请输入建议..."
              />
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <!-- AI 辅助诊断面板 -->
        <el-card class="ai-panel">
          <template #header>
            <div class="card-header">
              <span>AI 辅助诊断</span>
              <el-tag type="success">置信度: {{ aiAnalysis.confidence }}%</el-tag>
            </div>
          </template>

          <div class="ai-content">
            <!-- 诊断建议 -->
            <h4>鉴别诊断</h4>
            <el-collapse v-model="activeDiagnosis">
              <el-collapse-item
                v-for="diagnosis in aiAnalysis.diagnoses"
                :key="diagnosis.id"
                :title="diagnosis.name"
                :name="diagnosis.id"
              >
                <div class="diagnosis-detail">
                  <p>{{ diagnosis.description }}</p>
                  <div class="confidence-bar">
                    <el-progress
                      :percentage="diagnosis.probability"
                      :color="getConfidenceColor(diagnosis.probability)"
                    />
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>

            <!-- 相关文献 -->
            <h4 class="mt-4">相关文献</h4>
            <el-timeline>
              <el-timeline-item
                v-for="paper in aiAnalysis.papers"
                :key="paper.id"
                :timestamp="paper.year"
                placement="top"
              >
                <el-card>
                  <h4>{{ paper.title }}</h4>
                  <p class="paper-authors">{{ paper.authors }}</p>
                  <p class="paper-journal">{{ paper.journal }}</p>
                  <el-button type="primary" link @click="openPaper(paper.doi)">
                    查看原文
                  </el-button>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { jsPDF } from 'jspdf'
import html2canvas from 'html2canvas'

const route = useRoute()
const selectedTemplate = ref('')
const activeDiagnosis = ref(['1'])

// 报告模板
const templates = ref([
  { id: '1', name: '标准CT报告模板' },
  { id: '2', name: '肿瘤随访报告模板' },
  { id: '3', name: '术前评估报告模板' }
])

// 患者信息
const patientInfo = ref({
  name: '张三',
  examDate: '2024-03-15',
  examType: '胸部CT平扫+增强',
  examId: 'CT2024031501'
})

// 关键影像
const keyImages = ref([
  {
    id: 1,
    url: '/images/key1.jpg',
    description: '横断面：右肺上叶结节'
  },
  {
    id: 2,
    url: '/images/key2.jpg',
    description: '冠状面：淋巴结分布'
  },
  {
    id: 3,
    url: '/images/key3.jpg',
    description: '3D重建：血管关系'
  }
])

// 报告内容
const reportContent = ref({
  findings: '',
  diagnosis: '',
  suggestions: ''
})

// AI分析结果
const aiAnalysis = ref({
  confidence: 92,
  diagnoses: [
    {
      id: '1',
      name: '肺腺癌',
      probability: 85,
      description: '影像学特征高度符合早期肺腺癌表现，建议进一步活检确诊。'
    },
    {
      id: '2',
      name: '炎性假瘤',
      probability: 12,
      description: '部分影像特征与炎性假瘤相似，但可能性相对较低。'
    },
    {
      id: '3',
      name: '错构瘤',
      probability: 3,
      description: '密度特征与错构瘤有部分重叠，但形态学特征不典型。'
    }
  ],
  papers: [
    {
      id: 1,
      title: '基于深度学习的肺结节良恶性预测研究进展',
      authors: 'Wang et al.',
      journal: 'Radiology',
      year: '2024',
      doi: '10.1000/rad.2024.123'
    },
    {
      id: 2,
      title: '肺腺癌影像组学特征分析',
      authors: 'Li et al.',
      journal: 'European Radiology',
      year: '2023',
      doi: '10.1000/eur.2023.456'
    }
  ]
})

// 加载模板
const loadTemplate = (templateId: string) => {
  // 实现模板加载逻辑
  ElMessage.success('模板加载成功')
}

// 保存报告
const saveReport = async () => {
  try {
    // 实现保存逻辑
    ElMessage.success('报告保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 导出PDF
const exportPDF = async () => {
  try {
    const element = document.querySelector('.report-content') as HTMLElement
    if (!element) return

    // 使用html2canvas将内容转换为图片
    const canvas = await html2canvas(element, {
      scale: 2,
      useCORS: true,
      logging: false
    })

    // 创建PDF文档
    const pdf = new jsPDF('p', 'mm', 'a4')
    const imgWidth = 210 // A4纸的宽度(mm)
    const pageHeight = 297 // A4纸的高度(mm)
    const imgHeight = (canvas.height * imgWidth) / canvas.width
    let heightLeft = imgHeight
    let position = 0

    // 添加第一页
    pdf.addImage(canvas, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
    heightLeft -= pageHeight

    // 如果内容超过一页，添加新页面
    while (heightLeft >= 0) {
      position = heightLeft - imgHeight
      pdf.addPage()
      pdf.addImage(canvas, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
      heightLeft -= pageHeight
    }

    // 保存PDF
    pdf.save(`医学影像报告_${patientInfo.value.examId}.pdf`)
    ElMessage.success('PDF导出成功')
  } catch (error) {
    console.error('Error exporting PDF:', error)
    ElMessage.error('PDF导出失败')
  }
}

// 获取置信度颜色
const getConfidenceColor = (probability: number) => {
  if (probability >= 80) return '#67C23A'
  if (probability >= 50) return '#E6A23C'
  return '#F56C6C'
}

// 打开文献
const openPaper = (doi: string) => {
  window.open(`https://doi.org/${doi}`, '_blank')
}
</script>

<style scoped>
.report-view {
  padding: 20px;
}

.report-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-select {
  display: flex;
  align-items: center;
  gap: 10px;
}

.report-content {
  padding: 20px;
}

.report-header {
  margin-bottom: 20px;
}

.image-gallery {
  margin: 20px 0;
}

.key-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-caption {
  padding: 10px;
  font-size: 12px;
  color: #666;
}

.report-body {
  h4 {
    margin: 20px 0 10px;
  }
}

.ai-panel {
  position: sticky;
  top: 20px;
}

.ai-content {
  h4 {
    margin: 15px 0 10px;
  }
}

.diagnosis-detail {
  p {
    margin-bottom: 10px;
  }
}

.confidence-bar {
  margin-top: 10px;
}

.paper-authors,
.paper-journal {
  margin: 5px 0;
  color: #666;
  font-size: 12px;
}

.mt-4 {
  margin-top: 16px;
}
</style> 